import { ITargetMove } from "./interface/ITargetMove";

export class TragetMoveCharacterController3D implements ITargetMove {
    role: Laya.Sprite3D
    private _forwardlenth: Laya.Vector3;

    // 移动速度（米/秒）
    public moveSpeed: number = 20;
    // 旋转速度（度/秒）
    public rotateSpeed: number = 180;
    private character: Laya.CharacterController;
    private _animator: Laya.Animator;
    private _transform: Laya.Transform3D;
    constructor(role: any) {
        this.role = role;
        this._forwardlenth = new Laya.Vector3();
        this._transform = (this.role as Laya.Sprite3D).transform;

        this._animator = this.role.getComponent(Laya.Animator);
        this.character = this.role.getComponent(Laya.CharacterController) as Laya.CharacterController;
    }
    onUpdate(): void {
        if (this.isJoystickInput) {
            return
        }
    }

    private isJoystickInput: boolean = false
    onBegin(): void {
        this.isJoystickInput = true
    }

    onMove(curDis: number, curAngle: number, offsetAngle: number): void {
        curAngle =-curAngle;       
        let delatx = Math.cos(curAngle * Math.PI / 180);
        let delaty = Math.sin(curAngle * Math.PI / 180);
        console.log(delatx,delaty)
        this.apply(delatx,delaty)
        this._animator.play("Run_loop");
    }

    onEnd(): void {
        this.isJoystickInput = false;
        this._forwardlenth.setValue(0, 0, 0)
        this.character.move(this._forwardlenth)
        this._animator.play("Idle_loop");
    }


    apply(horizontal: any, vertical: any): void {

       var deltaTime = Laya.timer.delta / 1000;
        // 计算移动方向（基于当前朝向）
        const moveDirection = new Laya.Vector3();
        this._transform.getForward(moveDirection);
        moveDirection.y = 0; // Ensure movement is only on the XZ plane
        Laya.Vector3.normalize(moveDirection, moveDirection);
        Laya.Vector3.scale(moveDirection, -vertical * this.moveSpeed * deltaTime, moveDirection);

        // 计算旋转量
        const rotation = this._transform.localRotationEuler;
        rotation.y -= horizontal * this.rotateSpeed * deltaTime;

        // 应用运动
        this.applyMove(moveDirection, rotation);
    }


    applyMove(moveDirection: any, rotation: any): void {
        if (this.character) {
            this.character.move(moveDirection)
            this._transform.localRotationEuler = rotation;
        }
    }
}